use std::{env, fs, path::Path, process::Command};

fn main() {
    // This build script only runs its logic when targeting iOS.
    let target = env::var("TARGET").unwrap_or_default();
    if !target.contains("ios") {
        return;
    }

    // Allow users to opt-out of the automatic configuration.
    if env::var("AZUL_IOS_SETUP").unwrap_or_default() == "disable" {
        println!(
            "cargo:warning=AZUL_IOS_SETUP is disabled. Skipping automatic iOS project \
             configuration."
        );
        return;
    }

    // --- Prerequisite Checks ---
    check_xcode_cli_tools();
    check_ios_deploy();

    // --- Automatic Project Configuration ---
    // This part modifies the user's project to set up the Cargo runner.
    // We assume the CWD for the build script is the user's project root.
    let project_root = env::var("CARGO_MANIFEST_DIR").unwrap();
    println!(
        "cargo:warning=Azul is automatically configuring '{}' for iOS builds.",
        project_root
    );

    // Create .cargo/config.toml
    let cargo_dir = Path::new(&project_root).join(".cargo");
    fs::create_dir_all(&cargo_dir).unwrap();
    let config_path = cargo_dir.join("config.toml");
    let config_content = format!(
        r#"[target.aarch64-apple-ios]
runner = "scripts/ios-runner.sh"
"#
    );
    // Only write the file if it doesn't exist or doesn't have our runner.
    if !fs::read_to_string(&config_path)
        .unwrap_or_default()
        .contains("ios-runner.sh")
    {
        fs::write(config_path, config_content).unwrap();
        println!("cargo:warning=Created/updated .cargo/config.toml with iOS runner.");
    }

    // Create the runner script
    let scripts_dir = Path::new(&project_root).join("scripts");
    fs::create_dir_all(&scripts_dir).unwrap();
    let runner_path = scripts_dir.join("ios-runner.sh");
    let runner_content = r#"#!/bin/bash
# This script is auto-generated by Azul's build system.
set -e

# Cargo passes the path to the executable as the first argument.
EXECUTABLE_PATH="$1"
# We derive the .app bundle path from it (it's created by the user's build script).
APP_NAME=$(basename "$EXECUTABLE_PATH")
APP_BUNDLE_PATH="$(dirname "$EXECUTABLE_PATH")/${APP_NAME}.app"

echo "Deploying and launching ${APP_BUNDLE_PATH} on attached iOS device..."

# Use ios-deploy to install and launch the app.
# The --justlaunch flag tells it not to attach a debugger.
ios-deploy --bundle "${APP_BUNDLE_PATH}" --justlaunch
"#;
    fs::write(&runner_path, runner_content).unwrap();
    // Make the script executable.
    Command::new("chmod")
        .arg("+x")
        .arg(&runner_path)
        .status()
        .unwrap();

    println!("cargo:warning=Created scripts/ios-runner.sh for deploying to device.");
}

/// Checks if Xcode Command Line Tools are installed.
fn check_xcode_cli_tools() {
    let status = Command::new("xcode-select").arg("-p").status();
    match status {
        Ok(s) if s.success() => { /* All good */ }
        _ => {
            panic!(
                "Xcode Command Line Tools not found. Please run 'xcode-select --install' in your \
                 terminal."
            );
        }
    }
}

/// Checks if ios-deploy is installed.
fn check_ios_deploy() {
    let status = Command::new("ios-deploy").arg("--version").status();
    match status {
        Ok(s) if s.success() => { /* All good */ }
        _ => {
            panic!(
                "'ios-deploy' not found. Please install it by running 'brew install ios-deploy'."
            );
        }
    }
}
